package com.pig4cloud.pig.flow.handle;

import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.mobai.flow.handle.CamundaGetUserHandleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author mobai
 */
@Service("camundaGetUserHandle")
public class CamundaGetUserHandle implements CamundaGetUserHandleService {
	@Autowired
	private RemoteUserService remoteUserService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private HistoryService historyService;

	@Override
	public List<String> getUserIdListByRoles(String... ids) {
		R<List<String>> userListR = remoteUserService.listByRoleIds(ids);
		return userListR.getData();
	}

	@Override
	public List<String> getStartUser(DelegateExecution execution) {
		String processInstanceId = execution.getProcessInstanceId();

		String userId = "";
		try {
			HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
			userId = historicProcessInstance.getStartUserId();
		} catch (Exception e) {
			userId = String.valueOf(SecurityUtils.getUser().getId());
		}
		return List.of(userId);
	}
}
